package com.niit.serviceuser.controller;


import com.niit.servicecommon.entity.Order;
import com.niit.servicecommon.entity.User;
import com.niit.serviceuser.client.OrderClient;
import com.niit.serviceuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderClient orderClient;
    
    /**
     * 查询所有用户
     */
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    // 在service-user服务中调用了 service-order服务，并返回结果
    @GetMapping("/orders")
    public List<Order> getAllOrders() {
        return restTemplate.getForObject("http://localhost:8081/orders", List.class);
    }

    @GetMapping("/orders2")
    // 当前方法调用失败时，会调用getAllOrdersFallback方法
//    @HystrixCommand(fallbackMethod = "getAllOrdersFallback")
    public List<Order> getAllOrders2() {
        return orderClient.getAllOrders();
    }

    public List<Order> getAllOrdersFallback() {
        System.out.println("方法熔断了，执行熔断方法：getAllOrdersFallback");
        return null;
    }
    
    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    
    /**
     * 添加用户
     */
    @PostMapping
    public void addUser(@RequestBody User user) {
        userService.addUser(user);
    }
    
    /**
     * 更新用户
     */
    @PutMapping
    public void updateUser(@RequestBody User user) {
        userService.updateUser(user);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}